using System;
using System.Data;
using System.Data.OleDb;
using System.ComponentModel;
using System.Reflection;
using System.Collections;
using System.Drawing;
using System.Collections.Specialized;

using System.Web.UI;
using System.Web.UI.WebControls;

using Microsoft.CommerceServer.Runtime;
using Microsoft.CommerceServer.Runtime.Profiles;
using Microsoft.CommerceServer.Runtime.Targeting;
using Microsoft.CommerceServer.Runtime.Pipelines;
using Microsoft.CommerceServer.Runtime.Diagnostics;

namespace IBuysSpy
{
	//<summary>
	//  This class is a custom web control for displaying an ad or a discount. The control can be 
	//  added to the toolbox and provides design time experience. Page history is taken into account
	//  when displaying multiple ads or discounts on the same page. This control is not dependent on
	//  any other class of the Retail 2002 site.
	//</summary>
	[DefaultProperty("Text"),ToolboxData("<{0}:ContentItemControl runat=server></{0}:ContentItemControl>")]
	public class ContentItemControl  : System.Web.UI.WebControls.WebControl
	{
		public enum ContentSize
		{
			Banner, 
			NavBanner, 
			LinkExchange, 
			Half, 
			Square, 
			Button1, 
			Button2, 
			Micro, 
			Vertical
		};

		public enum ContentSelectionContext
		{
			Advertising, 
			Discounts
		};

		private string text;
		protected ContentSize sizeVal = ContentSize.Banner;
		protected string pageGroupVal = "All";
		protected ContentSelectionContext selectionContextVal = ContentSelectionContext.Advertising;
		protected bool traceModeVal = false;
		protected string cultureVal = System.Threading.Thread.CurrentThread.CurrentCulture.Name;
		protected ContentSelector cso;

		protected static Page pageObj = null;
		protected static string history = "";


		protected override void Render(System.Web.UI.HtmlTextWriter output)
		{
			if (pageObj!=Page)
				// history gets initialized when page is diff.
			{
				history = "";
				pageObj = Page;
			}
			StringCollection col = GetContent();
			if (col!=null)
			{
				output.Write(col[0]);
			}
		}


		public StringCollection GetContent()
		{
			CommerceContext ctx = CommerceContext.Current;
			string ctxt = selectionContextVal.ToString();

			cso = CommerceContext.Current.TargetingSystem.SelectionContexts[ctxt].GetSelector();

			if (cso!=null)
			{
				CommerceContext.Current.TargetingSystem.TargetingContextProfile["PageGroup"].Value = pageGroupVal;

				if (ctx.AuthenticationInfo.IsAuthenticated())
				{
					Profile userProfile = ctx.UserProfile;

					if (userProfile!=null)
					{
						cso.Profiles.Add("User", userProfile);
					}
				}

				cso.ItemsRequested = 1;
				cso.Size = sizeVal.ToString();

				cso.Profiles.Add("targetingContext", ctx.TargetingSystem.TargetingContextProfile);
				cso.TraceMode = traceModeVal;

				if (history!="")
				{
					cso.PageHistory = history;
				}

				StringCollection Ads = null;

				try
				{
					Ads = cso.GetContent();
				}
				catch
				{
				}

				history = cso.PageHistory;

				if (Ads!=null)
				{
					if (Ads.Count>0)
					{
						return Ads;
					}
				}

				return null;
			}
			else
			{
				return null;
			}
		}


		//======================================================================================
		// <summary> Protected, Shared
		//      This method returns the page groups that apply to content items. </summary>
		// <returns>DataTable</returns>
		//======================================================================================
		protected static DataTable SelectContentItemPageGroups()
		{

			string col = "u_pg_tag";
			string tblName = "page_group";

			string sqlCommand = String.Format("SELECT [{0}] FROM {1}", col, tblName);
			string connString = (string) CommerceContext.Current.Resources["Campaigns"]["connstr_db_Campaigns"];
			OleDbConnection conn = new OleDbConnection(connString);
			DataSet data = Execute(sqlCommand, tblName, conn);
			DataTable tbl;

			if (data!=null)
			{
				tbl = data.Tables[tblName];
				return tbl;
			}

			return null;
		}


		//========================================================================
		//  <summary> Protected, Shared
		//      Executes an sql command against the database. </summary>
		//  <param name="sqlCommand">String, the sql query to execute</param>
		//  <param name="tblName">String, the name of the database table against which the query is executed</param>
		//  <param name="conn">OleDbConnection, connection to Campaigns</param>
		//  <returns>DataSet</returns>
		//========================================================================
		protected static DataSet Execute(string sqlCommand, string tblName, OleDbConnection conn)
		{
			try
			{
				OleDbCommand cmd = new OleDbCommand(sqlCommand, conn);

				if (cmd!=null)
				{
					OleDbDataAdapter dataAdapter = new OleDbDataAdapter();

					if (dataAdapter!=null)
					{
						dataAdapter.SelectCommand = cmd;
						conn.Open();
						DataSet result = new DataSet();

						if (result!=null)
						{
							dataAdapter.Fill(result, tblName);
							conn.Close();
							return result;
						}
					}
				}
			}
			catch
			{

			}

			return null;
		}

		[Bindable(true), Category("Appearance"), DefaultValue("")]
		public string Text
		{
			get
			{
				return text;
			}

			set
			{
				text = value;
			}
		}

		[Browsable(false), Category("Appearance")]
		public override Color BackColor    
		{
			get
			{
				return base.BackColor;
			}

			set
			{
				base.BackColor = value;
			}
		}


		[Browsable(false), Category("Appearance")]
		public override Color BorderColor    
		{
			get
			{
				return base.BorderColor;
			}

			set
			{
				base.BorderColor = value;
			}
		}


		[Browsable(false), Category("Appearance")]
		public override BorderStyle BorderStyle    
		{
			get
			{
				return base.BorderStyle;
			}

			set
			{
				base.BorderStyle = value;
			}
		}


		[Browsable(false), Category("Appearance")]
		public override Unit BorderWidth    
		{
			get
			{
				return base.BorderWidth;
			}

			set
			{
				base.BorderWidth = value;
			}
		}


		[Browsable(false), Category("Appearance")]
		public override string CssClass    
		{
			get
			{
				return base.CssClass;
			}

			set
			{
				base.CssClass = value;
			}
		}


		[Browsable(false), Category("Appearance")]
		public override Color ForeColor    
		{
			get
			{
				return base.ForeColor;
			}

			set
			{
				base.ForeColor = value;
			}
		}


		[Browsable(false), Category("Appearance")]
		public override FontInfo Font    
		{
			get
			{
				return base.Font;
			}
		}


		[Browsable(false), Category("Appearance")]
		public override string AccessKey    
		{
			get
			{
				return base.AccessKey;
			}
			set
			{
				base.AccessKey = value;
			}
		}


		[Browsable(false), Category("Behavior")]
		public override string ToolTip    
		{
			get
			{
				return base.ToolTip;
			}

			set
			{
				base.ToolTip = value;
			}
		}


		[Browsable(false), Category("Behavior")]
		public override bool Enabled    
		{
			get
			{
				return base.Enabled;
			}

			set
			{
				base.Enabled = value;
			}
		}


		[Browsable(false), Category("Behavior")]
		public override bool EnableViewState    
		{
			get
			{
				return base.EnableViewState;
			}

			set
			{
				EnableViewState = value;
			}
		}


		[Browsable(false), Category("Behavior")]
		public override short TabIndex    
		{
			get
			{
				return base.TabIndex;
			}

			set
			{
				base.TabIndex = value;
			}
		}


		[Browsable(false), Category("Layout")]
		public override Unit Width    
		{
			get
			{
				return base.Width;
			}

			set
			{
				base.Width = value;
			}
		}


		[Browsable(false), Category("Layout")]
		public override Unit Height    
		{
			get
			{
				return base.Height;
			}

			set
			{
				base.Height = value;
			}
		}


		// The following are design-time and run-time properties specific to the ContentItem control.
		[Browsable(true), Category("Appearance")]
		public ContentSize Size    
		{
			get
			{
				return sizeVal;
			}
			set
			{
				sizeVal = value;
			}
		}


		[Browsable(true), Category("Misc")]
		public ContentSelectionContext SelectionContext    
		{
			get
			{
				return selectionContextVal;
			}
			set
			{
				selectionContextVal = value;
			}
		}


		[Browsable(false)]
		public string PageGroup    
		{
			get
			{
				return pageGroupVal;
			}
			set
			{
				DataTable tbl = SelectContentItemPageGroups();
				int rowIndex;
				string choices = null;
				string currRowVal = null;
				for(rowIndex=0; rowIndex<tbl.Rows.Count; rowIndex++)
				{
					currRowVal = tbl.Rows[rowIndex][0].ToString();
					if (value.Equals(currRowVal))
					{
						pageGroupVal = value;
						return;
					}
					else
					{
						choices += "'"+currRowVal+"', ";
					}
				}

				string validValues = choices.Remove(choices.Length-2, 2);
				string exMsg = "The value you entered for property 'PageGroup' is invalid. Value should be one of ";
				if (validValues!=null)
				{
					exMsg += validValues;
				}
				throw new Exception(exMsg);

			}
		}


		[Browsable(false)]
		public string Culture    
		{
			get
			{
				return cultureVal;
			}
			set
			{
				cultureVal = value;
			}
		}


		[Browsable(false)]
		public bool TraceMode    
		{
			get
			{
				return traceModeVal;
			}
			set
			{
				traceModeVal = value;
			}
		}


		[Browsable(false)]
		public ContentSelector ContentSelector    
		{
			get
			{
				return cso;
			}
		}
	}
}
